﻿using StudentInfo.Areas.AccountArea.Services;
using System.Web.Mvc;
using StudentInfo.Security.Services;
using StudentInfo.Security.Enums;

namespace StudentInfo.Security.Attributes
{
    public class PermissionsAttribute : AuthorizeAttribute
    {
        private readonly PermissionType requiredPermission;
        private readonly CrudType requiredCrud;

        public PermissionsAttribute(PermissionType requiredPermission, CrudType requiredCrud = CrudType.CanRead)
        {
            this.requiredPermission = requiredPermission;
            this.requiredCrud = requiredCrud;
        }

        public override void OnAuthorization(AuthorizationContext context)
        {
            var account = AccountService.GetByName(context.HttpContext.User.Identity.Name, true);

            if (account != null)
            {
                if (RolePermissionService.HasAccessByUser(account.Id, requiredPermission, requiredCrud))
                    return;
            }
            
            context.Result = new RedirectResult("~/AccountArea/Account/LogOn");
        }
    }
}